package com.nuanshui.heatedloan.controller.display.wallet;

import java.util.HashMap;
import java.util.List;

import com.nuanshui.heatedloan.msgcenter.constant.SmsMsgBizType;
import com.nuanshui.heatedloan.msgcenter.model.SmsPushMsgBody;
import com.nuanshui.heatedloan.userinfo.facade.UserStateService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.nuanshui.heatedloan.constant.FundActionState;
import com.nuanshui.framework.lang.MoneyUtil;
import com.nuanshui.framework.springContext.SpringPropertiesUtil;
import com.nuanshui.framework.utils.LogUtil;
import com.nuanshui.heatedloan.baseservice.facade.OrderNumGenerate;
import com.nuanshui.heatedloan.constant.GlobalParam;
import com.nuanshui.heatedloan.controller.BaseController;
import com.nuanshui.heatedloan.dal.IdTypeHandler;
import com.nuanshui.heatedloan.fund.enums.PaymentBizType;
import com.nuanshui.heatedloan.fund.facade.PayPasswordService;
import com.nuanshui.heatedloan.fund.facade.UserAccountBillService;
import com.nuanshui.heatedloan.fund.facade.UserBindAccountService;
import com.nuanshui.heatedloan.fund.facade.UserFreezeFundActionService;
import com.nuanshui.heatedloan.fund.facade.UserFundActionService;
import com.nuanshui.heatedloan.fund.model.CashingApplyInfo;
import com.nuanshui.heatedloan.fund.model.UserAccount;
import com.nuanshui.heatedloan.fund.model.UserFundAction;
import com.nuanshui.heatedloan.middleware.msgcenter.bean.Model;
import com.nuanshui.heatedloan.msgcenter.integration.MsgTools;
import com.nuanshui.heatedloan.msgcenter.model.AliSmsNotificationCodeTemp;
import com.nuanshui.heatedloan.userinfo.facade.UserService;
import com.nuanshui.heatedloan.userinfo.model.SimpleUserInfo;
import com.nuanshui.heatedloan.userinfo.tool.UserTool;

/**
 * 用户资金流动控制器
 * @ClassName: UserFundActionController 
 * @author guohao
 * @date Jan 7, 2016 11:15:25 AM 
 *
 */
@RequestMapping({"/user/wallet/"})
@RestController
public class UserWalletController extends BaseController {
	
	@Reference(url=GlobalParam.FUND_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.FUND_DUBBO_SERVER_VERSION)
	private UserFundActionService userFundActionService;
	@Reference(url=GlobalParam.FUND_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.FUND_DUBBO_SERVER_VERSION)
	private UserFreezeFundActionService userFreezeFundActionService;
	@Reference(url=GlobalParam.FUND_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.FUND_DUBBO_SERVER_VERSION)
	private UserBindAccountService userBindAccountService;

	@Reference(url=GlobalParam.FUND_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.FUND_DUBBO_SERVER_VERSION)
	private UserAccountBillService userAccountBillService;
	
	@Reference(url=GlobalParam.FUND_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.FUND_DUBBO_SERVER_VERSION)
	private PayPasswordService payPasswordService;
	
	@Reference(url=GlobalParam.USER_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.USER_DUBBO_SERVER_VERSION)
	private UserTool userTool;

	@Reference(url=GlobalParam.USER_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.USER_DUBBO_SERVER_VERSION)
	private UserService userService;

	@Reference(url=GlobalParam.USER_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.USER_DUBBO_SERVER_VERSION)
	private UserStateService userStateService;

	@Reference(url = GlobalParam.BASESERVICE_DUBBO_SERVER, timeout = GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.BASESERVICE_DUBBO_SERVER_VERSION)
	private OrderNumGenerate orderNumGenerate;

	@Autowired
	private MsgTools msgTools;
	


	private static final Logger  logger = LoggerFactory.getLogger("user_fund");

	/**
	 * 获取当前登录用户的资金
	 * @author guohao
	 * @date Jan 4, 2016 4:15:49 PM
	 */
	@RequestMapping(value = "loadUserTotalMoney",method = RequestMethod.POST)
	public String loadUserTotalMoney() {
		String userId = getCurrentUser().getId();
		LogUtil.info(logger, "获取当前登录用户的资金总额");
		HashMap<String,Object> map  = new HashMap<String, Object>();
		UserAccount userAccountAli =  userBindAccountService.loadUserPayAccount(userId, 1);
		UserAccount userAccountWx = userBindAccountService.loadUserPayAccount(userId, 2);
		SimpleUserInfo user =  userTool.getSimpleUserInfo(userId);
		//查询用户是否绑定手机号，支付密码
		boolean isBindPhone = userStateService.bindPhoneStatus(userId);
		boolean isSetPayPassword = payPasswordService.isSetPayPassword(userId);
		map.put("isSetPayPassword", isSetPayPassword);
		map.put("isBindPhone", isBindPhone);
		map.put("verified", user.isVerified());
		long  price = userFundActionService.loadTotalFund(userId).asLong();
		map.put("money",MoneyUtil.toDoubleString(price));
		map.put("isBindPayAccount",(userAccountAli!=null || userAccountWx!=null)); 
		LogUtil.info(logger, "获取当前登录用户的资金总额成功");
		return success(map);	
	}
	
	/**
	 * 用户提现金额
	 * @param 
	 * @author guohao
	 * @date Jan 4, 2016 5:59:02 PM
	 */
	@RequestMapping(value = "drawCash",method = RequestMethod.POST)
	public String  drawCash(Double money) {		
		long m  =  MoneyUtil.toPenny(money);
		if(m<=0) error("请输入提现金额");
		String userId = getCurrentUser().getId();
		LogUtil.info(logger, "用户提现 "+money+"元");
		synchronized (userId.intern()) {
			Long hasMoney = userFundActionService.loadTotalFund(userId).asLong();
			if(hasMoney<money) error("提现金额有误");
		    String dealNum = orderNumGenerate.getDealNum(PaymentBizType.WITHDRAW_CASH.getCode());
		    UserFundAction userFundAction =new UserFundAction();
		    userFundAction.setActionType(PaymentBizType.WITHDRAW_CASH.getCode());
		    userFundAction.setStatus(FundActionState.AUDICT);
		    userFundAction.setUserId(userId);
		    userFundAction.setMoney(-1*m);
		    userFundAction.setPlatform("ALI");
		    userFundAction.setDealNum(dealNum);
		    userFundActionService.saveUserFundAction(userFundAction);
			LogUtil.info(logger,userId+" 申请提现 "+money+"元成功");
		}	
		//发送短信        	 
		SmsPushMsgBody model = new SmsPushMsgBody();
		String  adminUserId = SpringPropertiesUtil.getPropertiestValue("admin.user.id");
		model.addDstUserId(adminUserId);
		model.setBizType(SmsMsgBizType.APPLY_DRAW_CASH);
		model.setTemplateCode(AliSmsNotificationCodeTemp.APPLY_DRAW_CASH.gettempCode());
    	msgTools.sendSmsMsg(model);
		return success();
	}
	
	
	
	
	/**
	 * 获取某种资金流转
	 * @param status 资金流转的状态
	 * @param fundActionType 资金流转的类型
	 * @author guohao
	 * @date Jan 4, 2016 7:07:02 PM
	 */
	@RequestMapping(value = "listUserFundAction",method = RequestMethod.POST)
	public String listUserFundAction(Integer status,Integer fundActionType,Pageable pager) {
		List<UserFundAction> userFundActions=  userFundActionService.findByActionType(getCurrentUser().getId(),fundActionType, status, pager);
		//User user = userService.getUserInfo(getCurrentUser().getId());
		//String userNick = user == null ? null : user.getNick();
		for(UserFundAction action :userFundActions) {
			action.setUserNick("您");
		}
		return success(userFundActions);	
	}
	
	/**
	 * 得到申请提现者的相关信息
	 * @author Junyan2015
	 * @date 2016年1月25日 下午5:41:40
	 * @param fundId 提现ID
	 * @return 
	 */
	@RequestMapping(value = "getCashingApplyUserInfo",method = RequestMethod.POST)
	public String getCashingApplyUserInfo(String fundId) {
		//提现相关信息
		CashingApplyInfo info = userFundActionService.getUserFundActionById(fundId);
		if(info == null) info = new CashingApplyInfo();
		info.setCash((info.getCash() == null ? 0 : info.getCash()) / 100); // 转化成单位 元, 是整数？
		return success(info);
	}

	/**
	 * 审核用户的提现行为
	 * @author Junyan2015
	 * @date 2016年1月25日 上午10:47:07
	 * @param fundId 提现ID
	 * @param isPass 是否通过审核，1为通过，0为不通过
	 * @return 成功为true，其余为false
	 */
	@RequestMapping(value = "checkCashing",method = RequestMethod.POST)
	public String checkUserCashing(String fundId, Integer isPass) {
		LogUtil.info(logger, "执行提现"+fundId+"，审核"+isPass);
		fundId = IdTypeHandler.encode(5259);
		boolean isOK = userFundActionService.checkUserCashing(fundId, isPass, null);
		return success(isOK);
	}
	
	public static void main(String[] args) {
		System.out.println(IdTypeHandler.encode(78));
	}
	
}
